package archer.framework.web.extension.jodd;


import archer.framework.utils.JSONUtils;
import archer.framework.utils.ValidateUtils;
import jodd.io.StreamUtil;
import jodd.json.JsonSerializer;
import jodd.util.StringPool;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * jodd json转化器
 *
 * @author christ
 * @date 2015/9/1
 */
public class JoddJsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {

    public final static Charset UTF8 = Charset.forName("UTF-8");

    protected Charset charset = UTF8;


    public JoddJsonHttpMessageConverter() {
        super(new MediaType("application", "json", UTF8), new MediaType("application", "*+json", UTF8));
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

        byte[] bytes = StreamUtil.readAvailableBytes(inputMessage.getBody());
        if (ValidateUtils.isNotEmpty(bytes)) {

            return JSONUtils.deserialize(new String(bytes,Charset.forName(StringPool.UTF_8)), clazz);
        }
        return null;
    }

    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

        OutputStream out = outputMessage.getBody();

        JsonSerializer serializer = new JsonSerializer().deep(true);
        String s = serializer.serialize(o);
        if (ValidateUtils.isNotEmpty(s)) {
            out.write(s.getBytes(charset));
        }
    }

    public Charset getCharset() {
        return charset;
    }

    public JoddJsonHttpMessageConverter setCharset(Charset charset) {
        this.charset = charset;
        return this;
    }
}